package com.generic.demo1;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * @ClassName People
 * @Description 主人类
 * @Author Kx
 * @Date 2025/3/25 18:56
 * @Version 1.0
 */
public class People<T extends Pet> {
    private String name;
    private T pet;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public T getPet() {
        return pet;
    }

    public void setPet(T pet) {
        this.pet = pet;
    }

    public People(String name, T pet) {
        this.name = name;
        this.pet = pet;
    }

    /***
     * @author: kx
     * @date: 2025/3/25 19:23
     * @description: 主人带宠物去逛街的方法(只能带温顺)
    */
    public void shopping(){
        try {
            // 获取BeanInfo对象
            BeanInfo beanInfo = Introspector.getBeanInfo(pet.getClass());

            // 获取所有属性
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            // 循环遍历所有属性
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
                // 判断是否与需要查询的属性名相同
                if (propertyDescriptor.getName().equals("trait")){
                    // 获取get方法
                    Method readMethod = propertyDescriptor.getReadMethod();

                    try {
                        Object invoke = readMethod.invoke(pet);
                        if (invoke.equals("温顺")){
                            System.out.println(name + "带" + pet.getName() + "去逛街");
                        } else {
                            System.out.println("主人只带温顺的宠物去逛街");
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        // 判断宠物是否会叫
        if (pet instanceof Call){
            ((Call) pet).call();
        }
    }
}
